<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}`">
    <el-form
      ref="examFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      :before-close="_colse"
    >
      <el-form-item label="考试名称" prop="testName">
        <el-input v-model="drawerProps.row!.testName" placeholder="请填写考试名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="试卷名称" prop="paperId">
        <el-select v-model="drawerProps.row!.paperId" placeholder="请选择试卷名称" clearable>
          <el-option v-for="item in examSelList" :key="item.paperId" :label="item.paperName" :value="item.paperId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考场名称" prop="roomName">
        <el-input v-model="drawerProps.row!.roomName" placeholder="请填写考场名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="监考老师" prop="teacherId">
        <el-select v-model="drawerProps.row!.teacherId" clearable placeholder="请选择监考老师">
          <el-option v-for="val in teacherSelList" :key="val.userId" :label="val.userName" :value="val.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试开始时间">
        <el-date-picker
          style="width: 200px"
          placeholder="请选择考试开始时间"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="drawerProps.row!.startTime"
        />
      </el-form-item>
      <el-form-item label="考试结束时间">
        <el-date-picker
          style="width: 200px"
          placeholder="请选择考试结束时间"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="drawerProps.row!.endTime"
        />
      </el-form-item>
      <el-form-item label="考试学生" prop="studentList">
        <el-select v-model="drawerProps.row!.studentList" multiple clearable placeholder="请选择考试学生">
          <el-option v-for="val in studentSelList" :key="val.userId" :label="val.userName" :value="val.userId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="CabineDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { ExamTest, ResultData } from "@/api/interface";
// import { CirclePlus } from "@element-plus/icons-vue";
import { getExamDtl } from "@/api/modules/examManage/examTest";
import { getExamPaperSelList } from "@/api/modules/examManage/examPaper";
import { getUserSelList } from "@/api/modules/user";
const rules = reactive({
  testName: [{ required: true, message: "请填写考试名称" }],
  paperId: [{ required: true, message: "请选择试卷名称" }],
  roomName: [{ required: true, message: "请填写考场名称" }],
  startTime: [{ required: true, message: "请选择考试开始时间" }],
  endTime: [{ required: true, message: "请选择考试结束时间" }],
  teacherId: [{ required: true, message: "请选择监考老师" }],
  studentList: [{ required: true, message: "请选择学生" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<ExamTest.ResExamTestList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}
const examSelList: any = ref([]);
const teacherSelList: any = ref([]);
const studentSelList: any = ref([]);

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;

  drawerProps.value.row.studentList = drawerProps.value.row.studentList ?? [];

  if (drawerProps.value.title === "编辑") {
    const { result } = (await getExamDtl({ testId: drawerProps.value.row.testId as number })) as ResultData;
    drawerProps.value.row.studentList = result.studentList.map((item: any) => {
      return item.studentId;
    });
  }
  getUserSelData("teacher");
  getUserSelData("student");
  getExamSelData();
};

// 提交数据（新增/编辑）
const examFormRef = ref<FormInstance>();
/**
 * 新增控制信息
 */
// const _addControlItem = () => {
//   controlList.value.push({ id: controlList.value.length + 1, deviceId: "", teacherId: "" });
// };
/**
 * 删除控制信息
 */
// const _delControlItem = (curIdx: number) => {
//   controlList.value.splice(curIdx, 1);
// };
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  examFormRef.value && examFormRef.value.resetFields();
};
/**
 * 获取用户选择列表
 */
const getUserSelData = async (userType: string) => {
  try {
    const res = await getUserSelList({ userType });
    userType === "teacher" && (teacherSelList.value = res.dataList);
    userType === "student" && (studentSelList.value = res.dataList);
  } catch (error) {}
};
/**
 * 获取试卷选择列表
 */
const getExamSelData = async () => {
  const { result } = (await getExamPaperSelList({ pageNum: 1, pageSize: 100000 })) as ResultData;
  examSelList.value = result.dataList;
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  examFormRef.value!.validate(async valid => {
    if (!valid) return;
    const studentListFilter = JSON.parse(JSON.stringify(drawerProps.value.row!.studentList)).map((value: any) => {
      return { studentId: value };
    });
    try {
      await drawerProps.value.api!({ ...drawerProps.value.row, studentList: studentListFilter });
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scope>
.handlerBar {
  width: 100%;
  .handlerBar__header {
    padding: 0 10px;
  }
}
.controlItem {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin: 20px 0 0;
  border: 1px solid #eeeeee;
  .deviceId {
    margin-right: 20px;
  }
  .delBtn {
    position: absolute;
    top: -8px;
    right: -8px;
    color: var(--el-color-danger);
    cursor: pointer;
  }
}
</style>
